package org.jeecg.demo.wx.util;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.demo.wx.config.WXConfig;
import org.jeecg.demo.wx.constant.CacheConstant;
import org.jeecg.demo.wx.constant.URLConstant;
import org.jeecg.demo.wx.response.WXLoginResponse;
import org.jeecg.demo.wx.response.WXTokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 功能描述
 * 小程序工具类
 *
 * @author: zgq
 * @date: 2024年01月28日 19:57
 */
@Component
public class WXApiUtil {

    @Autowired
    private WXConfig wxConfig;

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private RedisUtil redisUtil;
    public static final Logger logger = LoggerFactory.getLogger(WXApiUtil.class);

    public String getAccessToken() {
        String token = (String) redisUtil.get(CacheConstant.WX_ACCESS_TOKEN_KEY);
        if (Objects.nonNull(token)) {
            return token;
        }
        String url = String.format(URLConstant.WX_ACCESS_TOKEN_URL, wxConfig.getAppid(), wxConfig.getSecret());
        WXTokenResponse WXTokenResponse = httpUtil.get(url, WXTokenResponse.class);
        String access_token = WXTokenResponse.getAccess_token();
        if (Objects.isNull(access_token) || StrUtil.isBlank(access_token)) {
            logger.error("获取access_token失败");
            throw new RuntimeException("获取access_token失败");
        }
        Integer expires_in = WXTokenResponse.getExpires_in();
        redisUtil.set(CacheConstant.WX_ACCESS_TOKEN_KEY, access_token, expires_in);
        return access_token;
    }

    public WXLoginResponse login(String code) {
        String url = String.format(URLConstant.WX_LOGIN_URL, wxConfig.getAppid(), wxConfig.getSecret(), code);
        WXLoginResponse wxLoginResponse = httpUtil.get(url, WXLoginResponse.class);
        if (Objects.isNull(wxLoginResponse)) {
            logger.error("登录失败");
            throw new RuntimeException("登录失败");
        }
        String openid = wxLoginResponse.getOpenid();
        String session_key = wxLoginResponse.getSession_key();
        if (StringUtils.isBlank(openid) || StringUtils.isBlank(session_key)) {
            logger.error("openid or session_key is null，errcode：{}，errmsg：{}", wxLoginResponse.getErrcode(), wxLoginResponse.getErrmsg());
            throw new RuntimeException("登录失败");
        }
        return wxLoginResponse;
    }
}

